<template>
  <view class="center" id="center" v-if="isLogn">
    <view class="user-info">
      <image :src="vuex_user.profile_pic" class="image" />
      <view class="info">
        <view>{{ vuex_user.username }}</view>
        <view>手机:{{ vuex_user.mobile }}</view>
      </view>
    </view>

    <!-- 我的零食 -->
    <view class="my_foods">
      <view class="my_foods_title">
        <u-section
          title="我的订单"
          :show-line="false"
          :right="false"
          :bold="true"
          :font-size="30"
          color="#12202E"
        >
        </u-section>
      </view>
      <view class="builder-mode-list">
        <view
          v-for="(item, index) in orderListStatus"
          :key="index"
          @click="toOrder(item)"
        >
          <!-- <u-badge type="error" count="12" :is-center="false"></u-badge> -->
          <view class="badge-div">
            <!-- <view class="badge" >11</view> -->
            <uni-badge
              :text="item.num"
              v-show="item.tag"
              type="error"
              size="small"
            ></uni-badge>
          </view>
          <image :src="item.image" class="image" />
          <view class="order_status_title" style="margin-top: 20rpx">{{
            item.title
          }}</view>
        </view>
      </view>
    </view>

    <!-- 已经是楼长了  楼长管理 -->
    <view class="my_foods" v-if="jugeBuilderStatus() === 2 ? true : false">
      <view class="my_foods_title">
        <u-section
          title="商户管理"
          :right="false"
          :show-line="false"
          :bold="true"
          :font-size="30"
          color="#12202E"
        >
        </u-section>
      </view>
      <view class="builder-mode-list">
        <view
          v-for="(item, index) in builderModeList"
          :key="index"
          @click="toBuilder(item)"
        >
          <view :class="['iconfont', 'icon', item.icon]"></view>
          <view style="margin-top: 10rpx; color: '#5C6166'">{{
            item.title
          }}</view>
        </view>
      </view>
    </view>

    <!-- banner图 -->
    <swiper />

    <!-- 收货地址 -->
    <view class="resolve-address">
      <view class="my_address">
        <u-section
          title="收货地址"
          :right="true"
          :sub-title="notAddress ? '添加' : '编辑'"
          :bold="true"
          :show-line="false"
          :arrow="false"
          sub-color="#5C6166"
          @click="operateAddress"
          :font-size="30"
          color="#12202E"
        >
        </u-section>
      </view>
      <!-- 暂无收货地址 -->
      <view class="not-address" v-if="notAddress">
        <view>
          <u-empty text="暂无收货地址" :icon-size="80" mode="address"></u-empty>
        </view>
        <!-- <view @click="$refs.AddAddress.show = true">添加</view> -->
      </view>
      <view class="not-address" v-else>
        <view>
          <view>{{ vuex_address.linkman }} {{ vuex_address.linktel }}</view>
          <view style="margin-top: 10rpx">{{ vuex_address.address }}</view>
        </view>
        <!-- <view @click="editorAddress">编辑</view> -->
      </view>
    </view>

    <!-- 申请成为楼长 -->
    <view
      class="applicat-louzhang"
      @click="
        jugeBuilderStatus() === 1 ? $u.toast('楼长资料审核中') : toApplicat()
      "
      v-if="jugeShowApllicat()"
    >
      <view>
        <!-- status:1->待审核 2->审核通过  3->审核不通过 -->
        <u-section
          :title="jugeBuilderStatus() === 1 ? '商户资料审核中' : '申请成为商户'"
          :right="false"
          :bold="true"
          :show-line="false"
          :font-size="30"
          color="#12202E"
        >
        </u-section>
      </view>
      <view class="iconfont icon-xiayige"></view>
    </view>

    <view class="applicat-louzhang" @click="clearData">
      <view>
        <u-section
          title="清除缓存"
          :right="false"
          :show-line="false"
          :bold="true"
          :font-size="30"
          color="#12202E"
        >
        </u-section>
      </view>
      <view class="iconfont icon-xiayige"></view>
    </view>
    <!-- 新增地址弹窗 -->
    <add-address ref="AddAddress" />
  </view>

  <!-- 未登录 -->
  <view v-else class="no-login">
    <image
      src="https://qiniu.fleayun.cn/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20201214132835.png"
      class="image"
    />
    <view class="name"> 猫咪宜购</view>
    <!-- 注册 -->
    <!-- 先获取用户信息 -->
    <u-button
      type="success"
      shape="circle"
      @click="UserInfo"
      v-if="is_getUserInfo == true && isNotRegister == true"
      >微信授权登录</u-button
    >
    <u-button
      type="success"
      shape="circle"
      open-type="getPhoneNumber"
      v-else-if="is_getUserInfo == false && isNotRegister == true"
      @getphonenumber="getPhoneNumber"
      >手机快捷登录</u-button
    >
  </view>
</template>

<script>
import Swiper from "@/common/components/swiper";
import AddAddress from "./components/addAddress";
import uniBadge from "./components/uni-badge";
import { APPID, SECRET, WX_AUTH_URL } from "@/common/setting";
import store from "@/store";
export default {
  components: {
    Swiper,
    AddAddress,
    uniBadge,
  },
  data() {
    return {
      isLogn: false, //是否登录
      isNotRegister: false,
      notAddress: true,
      hasAddress: false,
      is_getUserInfo: true, //获取用户信息
      audit_status: "1", //楼长审核 通道
      apiForm: {
        //注册数据
        code: "",
        iv: "",
        encryptedData: "",
        username: "",
        profile_pic: "",
      },
      builderModeList: [
        {
          title: "用户订单",
          icon: "icon-dingdan",
          router: "/pages/builder/customOrder?index=0",
        },
        {
          title: "进货",
          icon: "icon-jinhuo",
          router: "/pages/builder/purchase",
        },
        {
          title: "进货订单",
          icon: "icon-icon-1",
          router: "/pages/builder/order?index=0",
        },
        {
          title: "提现",
          icon: "icon-yue1",
          router: "/pages/builder/withdraw",
        },
        {
          title: "设置",
          icon: "icon-shezhi1",
          router: "/pages/builder/setting",
        },
        {
          title: "开通提醒",
          icon: "icon-tongzhi",
          router: "/pages/builder/notice",
        },
        {
          title: "店铺码",
          icon: "icon-erweima",
          router: "/pages/builder/qrcode",
        },
      ],
      orderListStatus: [
        {
          image: "../../static/center/center_4.png",
          title: "待支付",
          tag: true,
          router: 1,
          num: 0,
        },
        {
          image: "../../static/center/center_2.png",
          title: "待发货",
          tag: true,
          router: 2,
          num: 0,
        },
        {
          image: "../../static/center/center_1.png",
          title: "待收货",
          tag: true,
          router: 3,
          num: 0,
        },
        {
          image: "../../static/center/center_3.png",
          title: "已完成",
          tag: false,
          router: 4,
        },
        {
          image: "../../static/center/center_5.png",
          title: "已取消",
          router: 5,
        },
      ],
    };
  },
  methods: {
    operateAddress() {
      if (this.notAddress) {
        this.$refs.AddAddress.show = true;
        return;
      }
      this.editorAddress();
    },
    /**
     * 判断是否展示申请楼长
     */
    jugeShowApllicat() {
      var status = this.jugeBuilderStatus();
      if (this.audit_status === "1") {
        return false;
      } else if (status === 1 || status === 3 || status === 4) {
        return true;
      } else {
        return false;
      }
    },
    /**
     * 判断 楼长审核状态
     */
    jugeBuilderStatus() {
      if (this.vuex_user.hasOwnProperty("status")) {
        if (this.vuex_user.status === 2) {
          return 2;
        } else if (this.vuex_user.status === 1) {
          return 1;
        } else {
          return 3;
        }
      } else {
        return 4;
      }
    },
    /**
     * 清除缓存
     */
    clearData() {
      var _this = this;
      uni.showModal({
        title: "提示",
        content: "确定清除缓存?",
        success: function (res) {
          if (res.confirm) {
            _this.$u.vuex("vuex_user", {});
            _this.$u.vuex("vuex_address", {});
            uni.reLaunch({
              url: "/pages/index/index",
            });
          }
        },
      });
    },
    /**
     * 跳转订单
     */
    toOrder(Info) {
      uni.navigateTo({
        url: "/pages/myfoods/myfoods?router=" + Info.router,
      });
    },

    /**
     * 申请楼长
     */
    toApplicat() {
      uni.navigateTo({
        url: "/pages/center/applicatInfo",
      });
    },

    /**
     * 登录 获取用户信息操作
     */
    async UserInfo() {
      // 务必放最外层
      await this.getUserInfo();
      await this.userLogin();
    },

    /**
     * 登录 获取用户手机号操作
     */
    getPhoneNumber(e) {
      console.log(e);
      this.userRegister(e).then(() => {
        return this.getUserCenterData();
      });
    },

    /**
     * 用户登录
     */
    userLogin() {
      let _this = this;
      return new Promise((resolve) => {
        uni.login({
          success: function (res1) {
            console.log(res1);
            _this.apiForm.code = res1.code;
            _this.$u.vuex("vuex_user_code", res1.code);
            resolve();
          },
        });
      });
    },

    /**
     * 获取用户信息
     */
    getUserInfo() {
      let _this = this;
      return new Promise((resolve) => {
        wx.getUserProfile({
          desc: "用于完善个人资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res2) => {
            console.log(res2);
            _this.apiForm.username = res2.userInfo.nickName;
            _this.apiForm.profile_pic = res2.userInfo.avatarUrl;
            // 获取用户信息后  再获取手机号
            _this.is_getUserInfo = false;
            _this.$u.toast("请再一次手机号授权登录");
            resolve();
          },
        });
        // uni.getUserInfo({
        //   provider: "weixin",
        //   success: function (res2) {
        //     console.log(res2);
        //     _this.apiForm.username = res2.userInfo.nickName;
        //     _this.apiForm.profile_pic = res2.userInfo.avatarUrl;
        //     // 获取用户信息后  再获取手机号
        //     _this.is_getUserInfo = false;
        //     _this.$u.toast("请再一次手机号授权登录");
        //     resolve();
        //   },
        // });
      });
    },

    /**
     * 用户注册
     */
    userRegister(e) {
      this.apiForm.encryptedData = e.detail.encryptedData;
      this.apiForm.iv = e.detail.iv;
      return new Promise((resolve) => {
        this.$u.api.registerApi(this.apiForm).then((res) => {
          var token = {
            token: res.token,
          };
          // 深度合并
          let vuex_user = this.$u.deepMerge(token, res.userinfo);
          this.$u.vuex("vuex_user", vuex_user);
          this.redirectBack();
          resolve();
          this.isLogn = true;
        });
      });
    },

    /**
     * 自动登录
     */
    autoLogin() {
      return new Promise((resolve) => {
        this.userLogin().then(() => {
          var form = {
            code: this.apiForm.code,
          };
          this.$u.api
            .autoLoginApi(form)
            .then((res) => {
              var token = {
                token: res.token,
              };
              // 深度合并
              let vuex_user = this.$u.deepMerge(token, res.userinfo);
              this.$u.vuex("vuex_user", vuex_user);

              this.redirectBack();
              resolve();
            })
            .catch((error) => {
              this.isNotRegister = true;
              this.$u.toast(error.message);
            });
        });
      });
    },

    /**
     * 获取用户中心数据
     */
    getUserCenterData() {
      return new Promise((resolve) => {
        this.$u.api
          .userCenterApi()
          .then((res) => {
            if (res.order_address === [] || res.order_address === null) {
              this.$u.vuex("vuex_address", {
                linkman: "",
                linktel: this.vuex_user.mobile,
                address: "",
              });
            } else {
              this.$u.vuex("vuex_address", res.order_address);
              this.notAddress = false;
              this.hasAddress = true;
            }
            // 店铺更新
            if (res.merchant_info.is_merchant === 1) {
              var user_info = this.vuex_user;
              user_info.status = res.merchant_info.info.status;
              user_info.is_merchant = res.merchant_info.is_merchant;
              user_info.announcement = res.merchant_info.info.announcement;
              user_info.wallet_amount = res.merchant_info.info.wallet_amount;
              user_info.open_status = res.merchant_info.info.open_status;
              this.$u.vuex("vuex_user", user_info);
            }

            // 处理订单状态
            this.orderListStatus[0].num = res.order_info.un_paid;
            this.orderListStatus[1].num = res.order_info.paid;
            this.orderListStatus[2].num = res.order_info.delivery;
            this.isLogn = true;
            uni.setNavigationBarTitle({
              title: this.isLogn == true ? "个人中心" : "登录",
            });
            uni.hideLoading();
            uni.stopPullDownRefresh();
          })
          .catch((err) => {
            this.$u.toast(err.message);
          });
      });
    },

    /**
     * 编辑地址
     */
    editorAddress() {
      this.$refs.AddAddress.isEditor = true;
      this.$refs.AddAddress.apiForm = this.vuex_address;
      this.$refs.AddAddress.show = true;
    },
    /**
     * 楼长管理 跳转
     */
    toBuilder(item) {
      uni.navigateTo({
        url: item.router,
      });
    },
    /**
     * 判断是否开通楼长审核
     */
    systemInfo() {
      this.$u.api.systemApi().then((res) => {
        this.audit_status = res.audit_status;
      });
    },
    /**
     * 从店铺首页跳转登录，需要返回源
     */
    redirectBack() {
      //  const pages = getCurrentPages(); //页面对象
      const prevpage = store.state.prev_page; //上一个页面对象
      const merchantInfo = store.state.merchant_info; //商户信息
      if (prevpage == "pages/shop/shop" && merchantInfo) {
        this.$u.route({
          url: "/pages/shop/shop",
          params: merchantInfo,
        });
      }
      // console.log(pages.length)
      // console.log(pages[pages.length - 1])
    },
  },

  onPullDownRefresh() {
    this.autoLogin().then(() => {
      return this.getUserCenterData();
    });
  },
  onShow() {
    uni.setNavigationBarTitle({
      title: this.isLogn == true ? "个人中心" : "登录",
    });
    uni.setNavigationBarColor({
      frontColor: "#000000", //文字颜色
      backgroundColor: "#ffffff", //底部背景色
    });

    if (this.vuex_user.hasOwnProperty("token")) {
      this.systemInfo();
      this.getUserCenterData();
    } else {
      this.autoLogin().then(() => {
        return this.getUserCenterData();
      });
    }
  },
  onLoad() {
    uni.showLoading({
      title: "加载中",
    });
  },
};
</script>

<style scoped lang ='scss' >
@mixin flex-row {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

@mixin shadow {
  box-shadow: 3rpx 5rpx 15rpx 5rpx #e6e6e6;
}

.center {
  padding: 30rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
  .user-info {
    @include flex-row;
    background-color: #ffffff;
    height: 200rpx;
    border-radius: 16rpx;
    padding: 20rpx 50rpx;
    @include shadow;
    .image {
      width: 150rpx;
      height: 150rpx;
      @include shadow;
      border-radius: 20rpx;
    }
    .info {
      color: #000000;
      font-size: 36rpx;
      font-weight: blod;
      margin-left: 40rpx;
      & > view:nth-child(2) {
        color: #000000;
        font-size: 24rpx;
        margin-top: 18rpx;
      }
    }
  }
  .my_foods {
    background-color: #ffffff;
    border-radius: 16rpx;
    margin: 20rpx 0;
    padding: 50rpx 30rpx;
    @include shadow;
    .builder-mode-list {
      display: grid;
      grid-template-columns: repeat(5, 20%);
      grid-template-rows: repeat(auto-fill, 150rpx);
      & > view {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .icon {
          color: #5c6166;
          font-size: 44rpx;
          margin-bottom: 5rpx;
        }
        .image {
          width: 41rpx;
          height: 36rpx;
        }
        .order_status_title {
          color: #5c6166;
          font-size: 28rpx;
        }
        .badge-div {
          width: 80%;
          height: 25rpx;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
    .my_foods_title {
      margin-bottom: 20rpx;
      color: #5c6166;
      font-size: 28rpx;
      font-weight: bold;
    }
  }
  .resolve-address {
    background-color: #ffffff;
    border-radius: 16rpx;
    @include shadow;
    /* margin: 20rpx 0 20rpx 0; */
    margin-top: 20rpx;
    padding: 30rpx;
    .my_address {
      margin-bottom: 50rpx;
      color: #333333;
      font-size: 28rpx;
      font-weight: bold;
    }
    .not-address {
      @include flex-row;
      min-height: 50rpx;
      max-height: 100rpx;
      & > view:nth-child(1) {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }
      & > view:nth-child(2) {
        width: 150rpx;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 28rpx;
        color: #000000;
        text-align: center;
        border-left: 1rpx solid #e6e6e6;
      }
    }
  }

  .applicat-louzhang {
    background-color: #ffffff;
    border-radius: 16rpx;
    width: 100%;
    margin: 20rpx 0;
    color: #333333;
    padding: 30rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    @include shadow;
  }
}

.no-login {
  padding: 200rpx 100rpx 100rpx 100rpx;
  text-align: center;
  .image {
    width: 200rpx;
    height: 200rpx;
  }
  .name {
    font-size: 44rpx;
    color: #333333;
    font-weight: bold;
    margin-top: 20rpx;
    margin-bottom: 100rpx;
  }
}
</style>
